<template>
  <el-select
      v-model="selectedValue"
      placeholder="请选择"
      class="filter-select"
      clearable
      :disabled="loading"
      @change="onChange"
  >
    <el-option
        v-for="item in sortedItems"
        :key="item.valueId"
        :label="item.valueNameCn"
        :value="item.valueName"
    >
      <template #default>
        <span>{{ item.valueNameCn }}</span>
        <el-tooltip v-if="item.remark" effect="dark" :content="'备注：' + item.remark" placement="top">
          <i class="el-icon-question filled-circle-icon"></i>
        </el-tooltip>
      </template>
    </el-option>
  </el-select>
</template>


<script>
import { ref, watch, onMounted , computed} from 'vue';
import {getDropdownInfo} from "@/service/admin/admin.service";

export default {
  name: 'DropdownDictSelect',
  props: {
    modelValue: {
      type: String,
      default: '',
    },
    dictName: {
      type: String,
      required: true,
    },
    spaceId: {
      type: Number,
      required: false,
    },
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const items = ref([]);
    const selectedValue = ref(props.modelValue);
    const loading = ref(true);

    // 获取字典数据
    const fetchData = () => {
      loading.value = true;
      getDropdownInfo(props.dictName, props.spaceId, (response) => {
        if (response.status === 'success') {
          items.value = response.data.items || [];
        } else {
          items.value = [];
        }
        loading.value = false;
      }, () => {
        items.value = [];
        loading.value = false;
      });
    };

    // 根据序号排序
    const sortedItems = computed(() => {
      return [...items.value].sort((a, b) => a.index - b.index);
    });

    // 监听 props 变化
    watch([() => props.dictName, () => props.spaceId], fetchData);

    // 监听 selectedValue 变化并向父组件更新
    watch(selectedValue, (newValue) => {
      emit('update:modelValue', newValue);
    });

    // 初始加载数据
    onMounted(fetchData);

    return {
      selectedValue,
      sortedItems,
      loading,
    };
  },
};
</script>

<style scoped>
.filled-circle-icon {
  font-size: 12px;
  color: #909399;
  margin-left: 4px;
}
</style>
